const {createServer} = require('http')
const {Server} = require('socket.io')

const app = createServer()
const IO = new Server(app,{
  path: '/websocket'
})

const chatRoom = {}
IO.on('connection', socket => {
  console.log('链接服务成功了')
  const userId = socket.handshake.query.id
  if(userId) {
    chatRoom[userId] = socket.id
  }
  socket.on('ping', () => {
    socket.emit('pang')
  })
  socket.on('sendMsg', info => {
    console.log('服务端接收到客户端发送的消息了,消息内容为', info)
    const toId = info.toId
    const toSocketId = chatRoom[toId]
    socket.to(toSocketId).emit('receiveMsg', info)
  })
})

app.listen(3000, () => {
  console.log('服务启动成功')
})